//
//  LocationNearbyViewController.m
//  jingjing2.0
//
//  Created by apple on 16/5/11.
//  Copyright © 2016年 apple. All rights reserved.
//

#import "LocationNearbyViewController.h"
#import <MAMapKit/MAMapKit.h>
#import <AMapSearchKit/AMapSearchAPI.h>
#import <AMapSearchKit/AMapSearchKit.h>

@interface LocationNearbyViewController ()<AMapSearchDelegate,MAMapViewDelegate,UITableViewDelegate,UITableViewDataSource>
@property(nonatomic,strong)UIScrollView *bgScrollView;
@property(nonatomic,strong)AMapSearchAPI *search;
@property(nonatomic,strong)MAMapView *mapView;
@property(nonatomic,strong)UILabel *cityLabel;
@property(nonatomic,strong)UILabel *tipLabel;
@property(nonatomic,strong)UITextField *tx;
@property(nonatomic,strong)UITableView *tableView;
@property(nonatomic,strong)NSMutableArray *dataSource;
@end

@implementation LocationNearbyViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title=@"位置选择";
    self.view.backgroundColor=[UIColor whiteColor];
    [self setUpSearchBarView];
    _dataSource=[NSMutableArray array];
    [self setUpLocationTableView];

   
}
#pragma mark--创建显示位置的表格
-(void)setUpLocationTableView
{
    _tipLabel=[[UILabel alloc]initWithFrame:CGRectMake(0, _cityLabel.frame.origin.y+250, kWidth, 30)];
    _tipLabel.backgroundColor=GRAYCOLOR;
    _tipLabel.text=@"您附近的收取地址";
    _tipLabel.textColor=BLUECOLOR;
    [self.view addSubview:_tipLabel];
    
    CGFloat heightY=_tipLabel.frame.origin.y+30;
    _tableView=[[UITableView alloc]initWithFrame:CGRectMake(0, heightY, kWidth, kHeight-heightY) style:UITableViewStylePlain];
    _tableView.delegate=self;
    _tableView.dataSource=self;
    [self.view addSubview:_tableView];
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataSource.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:@"reuse"];
    if (!cell)
    {
        cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"reuse"];
    }
    cell.selectionStyle=UITableViewCellSelectionStyleNone;
    LocationData *data=self.dataSource[indexPath.row];
    cell.textLabel.text=data.name;
    cell.detailTextLabel.text=data.datailAddress;

    return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    LocationData *data=self.dataSource[indexPath.row];
    [self isInServiceScope:data];
    [_tx resignFirstResponder];
}
#pragma mark--输入关键字找位置
-(void)setUpSearchBarView
{
    _cityLabel=[[UILabel alloc]initWithFrame:CGRectMake(0, 64, 80, 50)];
    _cityLabel.text=CURRENTCITY;
    _cityLabel.textAlignment=NSTextAlignmentCenter;
    _cityLabel.textColor=[UIColor blackColor];
    _cityLabel.backgroundColor=GRAYCOLOR;
    [self.view addSubview:_cityLabel];
    
    _tx=[[UITextField alloc]initWithFrame:CGRectMake(81, 64, kWidth-81, 50)];
    _tx.placeholder=@"请输入小区名或大厦名";
    _tx.backgroundColor=GRAYCOLOR;
    _tx.textColor=[UIColor blackColor];
    _tx.returnKeyType=UIReturnKeyDone;
    [_tx addTarget:self action:@selector(editingBegin:) forControlEvents:UIControlEventEditingDidBegin];
    [_tx addTarget:self action:@selector(editingOnExit:) forControlEvents:UIControlEventEditingDidEndOnExit];
    [_tx addTarget:self action:@selector(editingChanged:) forControlEvents:UIControlEventEditingChanged];
    [self.view addSubview:_tx];
    
}
-(void)editingBegin:(UITextField *)tx
{
    [_mapView removeFromSuperview];
    _tipLabel.frame=CGRectMake(0, _cityLabel.frame.origin.y+51, kWidth, 30) ;
    CGFloat heightY=_tipLabel.frame.origin.y+30;
    _tableView.frame=CGRectMake(0, heightY, kWidth, kHeight-heightY);
    _tipLabel.text=@"为您查找到的位置";

}

-(void)editingChanged:(UITextField *)tx
{
    [self.dataSource removeAllObjects];

    [self inputSearchWithKeyWords:tx.text];
}
-(void)editingOnExit:(UITextField *)tx
{
    [tx resignFirstResponder];
    //进行搜索
    [self inputSearchWithKeyWords:tx.text];
    
}
#pragma mark--定位与地图显示
-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    
    [GeneralTool showTabBar];
}
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
     [GeneralTool hideTabBar];
    //定位
    [self setUpMapView];
}
-(void)setUpMapView
{
    if (!_mapView)
    {
        //配置用户Key
        [MAMapServices sharedServices].apiKey = APIKEY;
        _mapView = [[MAMapView alloc]initWithFrame:CGRectMake(0, 114, CGRectGetWidth(self.view.bounds),200)];
        _mapView.delegate = self;
       self.mapView.userTrackingMode = MAUserTrackingModeFollow; // 追踪用户位置.
        _mapView.showsUserLocation = YES; //YES 为打开定位，NO为关闭定位
        [_mapView setUserTrackingMode: MAUserTrackingModeFollow animated:YES];
        [_mapView setZoomLevel:17.1 animated:YES];
        _mapView.showsCompass = NO;
        _mapView.showsScale = NO;
        _mapView.logoCenter =  CGPointMake(20.0f, _mapView.frame.size.height-20.0f);
        
        [self.view addSubview:_mapView];
    }

}
-(void)mapView:(MAMapView *)mapView didUpdateUserLocation:(MAUserLocation *)userLocation
updatingLocation:(BOOL)updatingLocation
{
    [_mapView setUserTrackingMode: MAUserTrackingModeNone animated:YES];
    if(updatingLocation)
    {
         _tipLabel.text=@"您附近的收取地址";
        if (!IsNilString(_tx.text)) {
            _tx.text=@"";
        }
        //取出当前位置的坐标
        CGFloat latitude = userLocation.coordinate.latitude;
        CGFloat longitude = userLocation.coordinate.longitude;
        NSLog(@"currentLocation:%@",userLocation);
        [self searchNearByWithLatitude:latitude andlongitude:longitude];
    }
    
}
#pragma mark--输入提示搜索
-(void)inputSearchWithKeyWords:(NSString *)keyWord;
{
    //配置用户Key
    [AMapSearchServices sharedServices].apiKey = APIKEY;
    
    //初始化检索对象
    _search = [[AMapSearchAPI alloc] init];
    _search.delegate = self;
    
    //构造AMapInputTipsSearchRequest对象，设置请求参数
    AMapInputTipsSearchRequest *tipsRequest = [[AMapInputTipsSearchRequest alloc] init];
    tipsRequest.keywords = keyWord;
    tipsRequest.city = CURRENTCITY;
    
    //发起输入提示搜索
    [_search AMapInputTipsSearch: tipsRequest];
}
//实现输入提示的回调函数
-(void)onInputTipsSearchDone:(AMapInputTipsSearchRequest*)request response:(AMapInputTipsSearchResponse *)response
{
    if(response.tips.count == 0)
    {
        return;
    }
    //通过AMapInputTipsSearchResponse对象处理搜索结果
    [response.tips enumerateObjectsUsingBlock:^(AMapTip *p, NSUInteger idx, BOOL * _Nonnull stop) {
        if (idx<=20) {
            LocationData *data=[[LocationData alloc]init];
            data.name=p.name;
            data.datailAddress=[NSString stringWithFormat:@"%@%@",p.district,p.name];
            data.Areacode=p.adcode;
            data.Longitude=p.location.longitude;
            data.Latitude=p.location.latitude;
            
            [self.dataSource addObject:data];
            [_tableView reloadData];
        }
    }];
}
#pragma mark--周边搜索
-(void)searchNearByWithLatitude:(CGFloat)Latitude andlongitude:(CGFloat)longitude
{
    [AMapSearchServices sharedServices].apiKey = APIKEY;
    //初始化检索对象
    _search = [[AMapSearchAPI alloc] init];
    _search.delegate = self;
    
    //构造AMapPOIAroundSearchRequest对象，设置周边请求参数
    AMapPOIAroundSearchRequest *request = [[AMapPOIAroundSearchRequest alloc] init];
    request.location = [AMapGeoPoint locationWithLatitude:Latitude longitude:longitude];
    request.types = @"商务住宅";
    request.sortrule = 0;
    request.requireExtension = YES;
    
    //发起周边搜索
   [_search AMapPOIAroundSearch: request];
    
}
//实现POI搜索对应的回调函数
- (void)onPOISearchDone:(AMapPOISearchBaseRequest *)request response:(AMapPOISearchResponse *)response
{
    if(response.pois.count == 0)
    {
        return;
    }
    [self.dataSource removeAllObjects];
    [response.pois enumerateObjectsUsingBlock:^(AMapPOI *p, NSUInteger idx, BOOL * _Nonnull stop) {
    if (idx<=20) {
            LocationData *data=[[LocationData alloc]init];
            data.name=p.name;
            data.datailAddress=[NSString stringWithFormat:@"%@%@%@",p.province,p.district,p.address];
            data.Areacode=p.adcode;
            data.Longitude=p.location.longitude;
            data.Latitude=p.location.latitude;
            [self.dataSource addObject:data];
        }
    }];
    [_tableView reloadData];
}
#pragma mark--判断位置是否在服务范围
-(void)isInServiceScope:(LocationData *)data
{
    NSString *timeStamp=[GeneralTool gettimestamp];
    NSString *longitude=[NSString stringWithFormat:@"%f",data.Longitude];
    NSString *latitude=[NSString stringWithFormat:@"%f",data.Latitude];
    if (_categoryID) {
        NSDictionary *signDic=@{@"CategoryID":_categoryID,
                                @"CityCode":GETCITYCODE,
                                @"Areacode":data.Areacode,
                                @"Longitude":longitude,
                                @"Latitude":latitude,
                                @"Timestamp":timeStamp};
        NSString *sign=[GeneralTool GetSin:signDic];
        NSDictionary *dic=@{@"CategoryID":_categoryID,
                            @"CityCode":GETCITYCODE,
                            @"Areacode":data.Areacode,
                            @"Longitude":longitude,
                            @"Latitude":latitude,
                            @"Timestamp":timeStamp,
                            @"Sign":sign};
        NSDictionary *dataDic=@{@"m_IsServiceAreaPara":dic};
        [RequestTool requestDataWithType:@"post" andUrlString:@"Common/IsServiceArea" andParameters:dataDic andRequestFinished:^(id responses, NSError *error) {
            if (error) {
                [MBProgressHUD showError:@"网络有点慢哦～"];
            }else
            {
                if ([responses[@"IsSuccess"]intValue]==1) {
                    //传值
                    _passLocationBlock(data);
                    [self.navigationController popViewControllerAnimated:YES];
                }else
                {
                    [MBProgressHUD showError:[responses[@"ReturnObject"]stringByRemovingPercentEncoding]];
                }
            }
        }];

    }
}
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}



@end
